package com.example.iot.queue.message;

import com.example.iot.entity.id.EntityId;
import com.example.iot.msg.TbMsg;
import com.google.gson.*;
import lombok.Data;
import java.lang.reflect.Type;
import java.util.Set;

/**
 * 队列实际消息体
 * @author ChenXiangpeng
 */
@Data
public final class RuleEngineQueueMsg extends SerializeBase {
    private final TbMsg msg;
    private final Set<String> relationTypes;
    private final String failureMessage;

    public RuleEngineQueueMsg(TbMsg msg, Set<String> relationTypes, String failureMessage) {
        this.msg = msg;
        this.relationTypes = relationTypes;
        this.failureMessage = failureMessage;
    }

    public static RuleEngineQueueMsg parseFrom(byte[] msg){
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(EntityId.class, new EntityAdapterFactory<RuleEngineQueueMsg>());
        Gson gson = gsonBuilder.create();
        return gson.fromJson(new String(msg), RuleEngineQueueMsg.class);
    }

    public static class EntityAdapterFactory<T> implements JsonSerializer<T>, JsonDeserializer<T> {
        @Override
        public JsonElement serialize(T object, Type interfaceType, JsonSerializationContext context) {
            final JsonObject wrapper = new JsonObject();
            wrapper.addProperty("type", object.getClass().getName());
            wrapper.add("data", context.serialize(object));
            return wrapper;
        }

        @Override
        public T deserialize(JsonElement elem, Type interfaceType, JsonDeserializationContext context) throws JsonParseException {
            final JsonObject wrapper = (JsonObject) elem;
            final JsonElement typeName = get(wrapper, "type");
            final JsonElement data = get(wrapper, "data");
            final Type actualType = typeForName(typeName);
            return context.deserialize(data, actualType);

        }


        private Type typeForName(final JsonElement typeElem) {
            try {
                return Class.forName(typeElem.getAsString());
            } catch (ClassNotFoundException e) {
                throw new JsonParseException(e);
            }
        }

        private JsonElement get(final JsonObject wrapper, String memberName) {
            final JsonElement elem = wrapper.get(memberName);
            if (elem == null){
                throw new JsonParseException("no '" + memberName + "' member found in what was expected to be an interface wrapper");
            }
            return elem;
        }
    }
}
